import { defineStore } from 'pinia'
import { asyncRoutes, basicRoutes } from '@/router/routes'
import type { RouteItem } from '@/router/types'

function hasPermission(route: RouteItem, roles: UserRoles, permissions: UserPermissions): boolean {
  // * 不需要权限直接返回true
  if (!route.meta?.requireAuth) return true

  const routeRole = (route.meta?.roles as UserRoles) || []
  const routePermission = (route.meta?.permissions as UserPermissions) || []

  // * 路由指定的角色包含任一登录用户角色或权限则判定有权限
  return roles.some((item) => routeRole.includes(item)) || permissions.some((item) => routePermission.includes(item))
}

function filterAsyncRoutes(
  routes: Array<RouteItem> = [],
  roles: UserRoles,
  permissions: UserPermissions
): Array<RouteItem> {
  const ret: any[] = []
  routes.forEach((route) => {
    if (hasPermission(route, roles, permissions)) {
      const curRoute: RouteItem = {
        ...route,
        children: []
      }
      if (route.children && route.children.length) {
        curRoute.children = filterAsyncRoutes(route.children, roles, permissions)
      } else {
        Reflect.deleteProperty(curRoute, 'children')
      }
      ret.push(curRoute)
    }
  })
  return ret
}

export const usePermissionStore = defineStore('permission', {
  state() {
    return {
      accessRoutes: [] as Array<RouteItem>
    }
  },
  getters: {
    routes(): Array<RouteItem> {
      return basicRoutes.concat(this.accessRoutes)
    },
    menus(): Array<RouteItem> {
      return this.accessRoutes.filter((route) => route.name && !route.isHidden)
    }
  },
  actions: {
    generateRoutes(roles: UserRoles = [], permissions: UserPermissions = []) {
      const accessRoutes = filterAsyncRoutes(asyncRoutes, roles, permissions)
      this.accessRoutes = accessRoutes
      return accessRoutes
    },
    resetPermission() {
      this.$reset()
    }
  }
})
